package com.leyou.gateway.filters;

import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
// 登录拦截，可以采用最高优先级！
@Order(1)
public class LoginFilter implements GlobalFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //重置过期时间
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            //获取ServerHttpRequest
            ServerHttpRequest request = exchange.getRequest();
            //获取token
            String token = request.getCookies().toSingleValueMap().get("KY_TOKEN").getValue();
            //获取token解析载荷部分
            Payload payload = jwtUtils.parseJwt(token);
            //Redis中存储Jti的key
            String redisJtiKey = RedisConstants.JTI_KEY_PREFIX + payload.getUserDetail().getId();
            //expire更新Redis中的JTI失效时间
            redisTemplate.expire(redisJtiKey, 30, TimeUnit.MINUTES);
            log.info("重置过期时间OK");
        } catch (Exception e) {
            // 解析失败，token有误
            log.info("用户未登录,或Jti已过期");
        }
        //执行完成业务后放行
        return chain.filter(exchange);
    }
}
